﻿package  {
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.display.SimpleButton;
	import flash.text.TextField;
	
	import com.greensock.TweenLite;
	import com.greensock.easing.Linear;
	import flash.utils.Timer;
	import flash.events.TimerEvent;
	import flash.display.BlendMode;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	
	public class LevelPreCut extends Level{
		protected var startPosition:Point;
		protected var candleTimer:Timer = new Timer(1);
		
		protected var kitty:MovieClip;
		protected var catSpeech:MovieClip;
		
		protected var doneMC:SimpleButton;
		protected var candleButtonMC:MovieClip;
		protected var potMC:MovieClip;
		protected var timeLeftText:TextField;
		protected var blackoutFilterMC:MovieClip;
		protected var candleHolderMC:MovieClip;
		protected var recipeMC:MovieClip;
		protected var windowMC:MovieClip;
		
		protected var theCandle:MovieClip;
		protected var candleOut:Boolean = false;
		
		private var bgm:Sound = new HappyBGM();
		private var bgmSoundChannel:SoundChannel = new SoundChannel();
		
		public function LevelPreCut() {
			gotoAndStop(1);
			
			super();
			
			addEventListener(Event.ADDED_TO_STAGE, onAdded);
		}
		
		protected function onAdded(e:Event):void{
			removeEventListener(Event.ADDED_TO_STAGE, onAdded);
			
			bgmSoundChannel = bgm.play();
			bgmSoundChannel.addEventListener(Event.SOUND_COMPLETE, loopSound);
			
			kitty = this["cat"] as MovieClip;
			catSpeech = this["speechBubble"] as MovieClip;
			recipeMC = this["recipe"] as MovieClip;
			windowMC = this["window"] as MovieClip;
			
			catSpeech.visible = false;
			recipeMC.alpha = 0;
			recipeMC.gotoAndStop(LevelNumber);
			windowMC.lightning.stop();
			
			TweenLite.from(kitty, 2, {y:450, onComplete:
				function kittySpeak():void{
					catSpeech.visible = true;
					catSpeech.speech.text = CatSpeech;
					trace(catSpeech.speech.text);
					catSpeech.addEventListener(MouseEvent.CLICK, dismissSpeech);
				}
			});
		}
		
		private function loopSound(e:Event):void{
			bgmSoundChannel = bgm.play();
			bgmSoundChannel.addEventListener(Event.SOUND_COMPLETE, loopSound);
		}
		
		protected function dismissSpeech(e:MouseEvent):void{
			catSpeech.visible = false;
			TweenLite.to(recipeMC, 2, {alpha:1});
			TweenLite.to(kitty, 2, {delay:2, y:450, ease:Linear.easeNone, onComplete:
				function kittyLeave():void{
					TweenLite.to(recipeMC, 1, {delay:2, alpha:0, ease:Linear.easeNone, onComplete:
						function(){
							Util.safeRemove(recipeMC);
							
							var delayTimer:Number = Constants.RECIPE_DELAY;
							addEventListener(Event.ENTER_FRAME, 
								function delay():void{
									delayTimer -= 1.0/stage.frameRate;
									if (delayTimer <= 0){
										removeEventListener(Event.ENTER_FRAME, delay);
										if (windowMC != null){
											var lightning:MovieClip = windowMC.lightning;
											lightning.play();
											lightning.addFrameScript(16,
												function(){
													//REMOVE FRAME SCRIPT
													lightning.addFrameScript(16, function(){});
													gotoAndStop(2);
													onStart();
												}
											);
										}
									}
								}
							);
						}
					});
				}
			});
		}
		
		protected function onStart():void{
			bgmSoundChannel.removeEventListener(Event.SOUND_COMPLETE, loopSound);
			bgmSoundChannel.stop();
			bgm = new DarkBGM();
			bgmSoundChannel = bgm.play();
			bgmSoundChannel.addEventListener(Event.SOUND_COMPLETE, loopSound);
			
			doneMC = this["done"] as SimpleButton;
			candleButtonMC = this["candleButton"] as MovieClip;
			
			if (Settings.CandlesLeft <= 0)
				candleButtonMC.gotoAndStop(4);
			else{
				trace(Settings.CandlesLeft);
				candleButtonMC.gotoAndStop(Settings.CandlesLeft);
			}
				
			potMC = this["pot"] as MovieClip;
			timeLeftText = this["timeLeft"] as TextField;
			blackoutFilterMC = this["blackoutFilter"] as MovieClip;
			candleHolderMC = this["candleHolder"] as MovieClip;
			
			for (var i:int = 0; i < this.numChildren; i++){
				if (this.getChildAt(i) as Ingredient != null){
					var mc:MovieClip = this.getChildAt(i) as MovieClip;
					mc.gotoAndStop(2);
				}
			}
			
			setTime(LevelTimer);
			
			addTimer();
			addListeners();
			addUiListeners();
		}
		
		protected function addTimer():void{
			addEventListener(Event.ENTER_FRAME, update);
		}
		
		protected function removeTimer():void{
			removeEventListener(Event.ENTER_FRAME, update);
		}
		
		protected function addListeners():void{
			for (var i:int = 0; i < this.numChildren; i++){
				if (this.getChildAt(i) as Ingredient != null){
					var mc:MovieClip = (this.getChildAt(i) as MovieClip);
					mc.buttonMode = true;
					mc.addEventListener(MouseEvent.MOUSE_DOWN, onDownIngredient);
				}
			}
		}
		
		protected function removeListeners():void{
			for (var i:int = 0; i < this.numChildren; i++){
				if (this.getChildAt(i) as Ingredient != null){
					var mc:MovieClip = (this.getChildAt(i) as MovieClip);
					mc.buttonMode = false;
					mc.removeEventListener(MouseEvent.MOUSE_DOWN, onDownIngredient);
					mc.removeEventListener(MouseEvent.MOUSE_UP, onUpIngredient);
				}
			}
		}
		
		protected function addUiListeners():void{
			doneMC.addEventListener(MouseEvent.CLICK, onDoneClick);
			if (Settings.CandlesLeft > 0 && candleButtonMC != null)
				candleButtonMC.addEventListener(MouseEvent.CLICK, onCandleClick);
		}
		
		protected function removeUiListeners():void{
			doneMC.removeEventListener(MouseEvent.CLICK, onDoneClick);
			if (Settings.CandlesLeft > 0 && candleButtonMC != null)
				candleButtonMC.removeEventListener(MouseEvent.CLICK, onCandleClick);
		}
		
		protected function update(e:Event):void{
			updateTimer();
		}
		
		protected function updateTimer():void{
			LevelTimer -= 1.0/stage.frameRate;
			setTime(LevelTimer);
			if (LevelTimer < 0){
				//End Level
				timeUp();
			}
		}
		
		protected function setTime(time:Number):void{
			var str:String;
			if (time >= 60){
				str = Util.addZeros(1,2);
				time -= 60;
			}else{
				str = "00";
			}
			timeLeftText.text = str + ":" + Util.addZeros(int(time),2);
		}
		
		protected function onCandleClick(e:MouseEvent):void{
			if (candleOut)
				return;
				
			candleOut = true;
			removeListeners();
			removeUiListeners();
			
			//Util.safeRemove(candleButtonMC);
			candleButtonMC.gotoAndStop(4);
			Settings.CandlesLeft--;
			
			var candle:MovieClip = new Candle();
			candle.x = this.mouseX; candle.y = this.mouseY;
			candleHolderMC.addChild(candle);
			theCandle = candle;
			theCandle.startDrag(true);
			
			addEventListener(MouseEvent.MOUSE_UP,
				function mouseUp(){
					removeEventListener(MouseEvent.MOUSE_UP, mouseUp);
					addEventListener(MouseEvent.CLICK, placeCandle);
				}
			);
		}
		
		protected function placeCandle(e:MouseEvent):void{
			removeEventListener(MouseEvent.CLICK, placeCandle);
			addListeners();
			
			addUiListeners();
			
			theCandle.stopDrag();
			
			this.createInvertedMask(blackoutFilterMC, new Point(theCandle.x, theCandle.y));
			
			for (var i:int = 0; i < this.numChildren; i++){
				if (this.getChildAt(i) as Ingredient != null){
					var mc:MovieClip = this.getChildAt(i) as MovieClip;
					var theMask:Sprite = blackoutFilterMC.getChildAt(1) as Sprite;
					if (theMask.hitTestObject(mc)){
						mc.gotoAndStop(1);
					}
				}
			}
			
			candleTimer = new Timer(1000 * Constants.CANDLE_TIME[Settings.Difficulty]);
			candleTimer.addEventListener(TimerEvent.TIMER, killCandle);
			candleTimer.start();
		}
		
		protected function killCandle(e:TimerEvent):void{
			//var timer:Timer = (e.target as Timer);
			candleOut = false;
			if (Settings.CandlesLeft <= 0)
				candleButtonMC.gotoAndStop(4);
			else
				candleButtonMC.gotoAndStop(Settings.CandlesLeft);
			candleTimer.stop();
			candleTimer.removeEventListener(TimerEvent.TIMER_COMPLETE, killCandle);
			Util.safeRemove(theCandle);
			var theMask:Sprite = blackoutFilterMC.getChildAt(1) as Sprite;
			Util.safeRemove(theMask);
			blackoutFilterMC.blendMode = BlendMode.NORMAL;
			
			for (var i:int = 0; i < this.numChildren; i++){
				if (this.getChildAt(i) as Ingredient != null){
					var mc:MovieClip = this.getChildAt(i) as MovieClip;
					mc.gotoAndStop(2);
				}
			}
		}
		
		protected function onDownIngredient(e:MouseEvent):void{
			var mc:MovieClip = (e.target as MovieClip);
			trace("You Grabbed:",mc.name)
			
			mc.parent.addChildAt(mc, mc.parent.getChildIndex(candleHolderMC)-1);
			removeListeners();
			mc.addEventListener(MouseEvent.MOUSE_UP, onUpIngredient);
			
			startPosition = new Point(mc.x, mc.y);
			
			mc.startDrag();
		}
		
		protected function onUpIngredient(e:MouseEvent):void{
			var mc:MovieClip = (e.target as MovieClip);
			mc.removeEventListener(MouseEvent.MOUSE_UP, onUpIngredient);
			//mc.addEventListener(MouseEvent.MOUSE_DOWN, onDownIngredient);
			addListeners();
			
			mc.stopDrag();
			
			if (mc.hitTestObject(potMC)){
				mc.removeEventListener(MouseEvent.MOUSE_DOWN, onDownIngredient);
				YourIngredients.push(mc.name);

				trace(mc.name);
				trace(YourIngredients.length);
				Util.safeRemove(mc);
			}else{
				mc.x = startPosition.x; mc.y = startPosition.y;
			}
		}
		
		protected function timeUp():void{
			lightsOnSequence();
		}
		
		protected function onDoneClick(e:MouseEvent):void{
			lightsOnSequence();
		}
		
		protected function lightsOnSequence():void{
			cleanUp();
			
			//Lights Turning on and such
			//Players see their soup
			//Then move to results Screen
			
			gotoAndStop(3);
			potMC.soup.gotoAndStop(SoupName);
			for (var i:int = 0; i < this.numChildren; i++){
				if (this.getChildAt(i) as Ingredient != null){
					var mc:MovieClip = this.getChildAt(i) as MovieClip;
					mc.gotoAndStop(1);
				}
			}
			
			var delayTimer:Number = 2.0;
			addEventListener(Event.ENTER_FRAME, 
				function delay():void{
					delayTimer -= 1.0/stage.frameRate;
					if (delayTimer <= 0){
						removeEventListener(Event.ENTER_FRAME, delay);
						showResults();
						windowMC.lightning.gotoAndStop(1);
					}
				}
			);
		}
		
		protected function cleanUp():void{
			doneMC.visible = false;
			
			removeListeners();
			removeUiListeners();
			removeTimer();
			
			candleTimer.stop();
			candleTimer.removeEventListener(TimerEvent.TIMER_COMPLETE, killCandle);
			
			bgmSoundChannel.removeEventListener(Event.SOUND_COMPLETE, loopSound);
			bgmSoundChannel.stop();
		}

	}
	
}
